package com.lws.basic.utils.common;

import java.math.BigInteger;
import java.nio.charset.Charset;

/**
 * @松 on 2019/7/28 21:00
 */
public class ByteDataUtils {

    //字节转二进制
    public static  String binary(byte[] bytes, int radix){
        return new BigInteger(1, bytes).toString(radix);// 这里的1代表正数
    }

    //复制字节
    public static byte[] subBytes(byte[] src, int begin, int count) {
        byte[] bs = new byte[count];
        System.arraycopy(src, begin, bs, 0, count);
        return bs;
    }

    public static byte[] getBytes(float data) {
        int intBits = Float.floatToIntBits(data);
        return getBytes(intBits);
    }


    public static byte[] getBytes(double data) {
        long intBits = Double.doubleToLongBits(data);
        return getBytes(intBits);
    }


    public static byte[] getBytes(String data, String charsetName) {
        Charset charset = Charset.forName(charsetName);
        return data.getBytes(charset);
    }


    public static byte[] getBytes(String data) {
        return getBytes(data, "GBK");
    }

    // 使用两个 for 语句
//java 合并两个byte数组
        public static byte[] byteMerger(byte[] bt1, byte[] bt2){
            if(bt1.length!=0) {
                byte[] bt3 = new byte[bt1.length + bt2.length];
                System.arraycopy(bt1, 0, bt3, 0, bt1.length);
                System.arraycopy(bt2, 0, bt3, bt1.length, bt2.length);
                return bt3;
            }
            return bt2;

        }

    public static short getShort(byte[] bytes) {
        return (short) ((0xff & bytes[0]) | (0xff00 & (bytes[1] << 8)));
    }


    public static char getChar(byte[] bytes) {
        return (char) ((0xff & bytes[0]) | (0xff00 & (bytes[1] << 8)));
    }


    public static int getInt(byte[] bytes) {
        return (0xff & bytes[0]) | (0xff00 & (bytes[1] << 8)) | (0xff0000 & (bytes[2] << 16)) | (0xff000000 & (bytes[3] << 24));
    }

    public static long getLong(byte[] bytes) {
        return (0xffL & (long) bytes[0]) | (0xff00L & ((long) bytes[1] << 8)) | (0xff0000L & ((long) bytes[2] << 16)) | (0xff000000L & ((long) bytes[3] << 24))
                | (0xff00000000L & ((long) bytes[4] << 32)) | (0xff0000000000L & ((long) bytes[5] << 40)) | (0xff000000000000L & ((long) bytes[6] << 48)) | (0xff00000000000000L & ((long) bytes[7] << 56));
    }


    public static float getFloat(byte[] bytes) {
        return Float.intBitsToFloat(getInt(bytes));
    }


    public static double getDouble(byte[] bytes) {
        long l = getLong(bytes);

        return Double.longBitsToDouble(l);
    }
    public static double bytes2Double(byte[] arr) {
        long value = 0;
        for (int i = 0; i < 8; i++) {
            value |= ((long) (arr[i] & 0xff)) << (8 * i);
        }
        return Double.longBitsToDouble(value);
    }


    public static String getString(byte[] bytes, String charsetName) {
        return new String(bytes, Charset.forName(charsetName));
    }



}
